package com.lonelyzhe.springboot.controller;


import com.lonelyzhe.springboot.bean.vo.Item;
import com.lonelyzhe.springboot.bean.vo.OrderInfoWithItem;
import com.lonelyzhe.springboot.service.impl.CartService;
import com.ruoyi.common.core.domain.AjaxResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;

@Controller
@RequestMapping("cart")
@ResponseBody
public class CartController {

    @Autowired
    CartService cartService;

    @RequestMapping("/add")
    public AjaxResult addItem(@RequestBody Item item) {
        try {
            cartService.addItem(item);
            return AjaxResult.success("操作成功");
        } catch (Exception e) {
//            e.printStackTrace();
            // 默认错误是500
            return AjaxResult.error("发生错误");
            // return error(AjaxResult.Type.WARN, "发生错误");
        }
    }

    @RequestMapping("/getcart")
    public AjaxResult getCart(@RequestParam("user_id") int user_id) {
        try {
            OrderInfoWithItem cart = cartService.selectCart(user_id);
            return AjaxResult.success(cart);
        } catch (Exception e) {
//            e.printStackTrace();
            // 默认错误是500
            return AjaxResult.error("发生错误");
            // return error(AjaxResult.Type.WARN, "发生错误");
        }
    }

    @RequestMapping("/changenum")
    public AjaxResult changeNum(@RequestParam("item_id") int item_id,@RequestParam("num")int num) {
        try {
            cartService.changeItemNum(item_id,num);
            return AjaxResult.success();
        } catch (Exception e) {
//            e.printStackTrace();
            // 默认错误是500
            return AjaxResult.error("发生错误");
            // return error(AjaxResult.Type.WARN, "发生错误");
        }
    }

    @RequestMapping("/submit")
    public AjaxResult changeNum(@RequestParam("order_id") int order_id) {
        try {
            cartService.submitOrder(order_id);
            return AjaxResult.success();
        } catch (Exception e) {
            return AjaxResult.error("发生错误");
        }
    }

    @RequestMapping("/delete")
    public AjaxResult deleteItem(@RequestParam("item_id") int item_id) {
        try {
            cartService.deleteItem(item_id);
            return AjaxResult.success();
        } catch (Exception e) {
            return AjaxResult.error("发生错误");
        }
    }


}
